package site.jlopen.assets.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.entity.vo.LoginRes;
import site.jlopen.service.intf.user.UserService;

/**
 * 自定义realm
* @ClassName: CustomerRealm
* @Description: <p>TODO</p>
* @author ChenJiaLu
* @date 2022年1月18日 下午5:52:21
*
 */
public class WebRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	//@Autowired
	//private SysLogService logService;
 
	@Override
	public boolean supports(AuthenticationToken token) {
	    return token instanceof UsernamePasswordToken;
	}
	
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles=new HashSet<>();
        roles.add("ADMIN");
        simpleAuthorizationInfo.addRoles(roles);
        //simpleAuthorizationInfo.addStringPermission(roleStr);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    	// 根据身份信息
        String principal = (String) token.getPrincipal();
        LoginRes user = userService.getLoginByName(principal);
        if(null == user){
            throw new UnknownAccountException("账号或密码错误");
        }
 		Subject subject = SecurityUtils.getSubject();
  		subject.getSession().setAttribute(ThreadAuthUser.USER_SESSION, user);
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes("carro"), this.getName());
    }
}
